import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
from datetime import datetime
from tkcalendar import DateEntry
from ui import frames
from tkinter import filedialog
from data_manager import data_manager
# 全局变量，用于追踪被拖动的卡片
dragged_card = None
drag_data = {"x": 0, "y": 0}

def on_press(event, card_frame):
    global dragged_card, drag_data
    dragged_card = card_frame
    drag_data["x"] = event.x
    drag_data["y"] = event.y
    card_frame.lift()  # 将当前卡片提升到最上层

def on_drag(event):
    global dragged_card
    if dragged_card:
        delta_x = event.x - drag_data["x"]
        delta_y = event.y - drag_data["y"]
        x = dragged_card.winfo_x() + delta_x
        y = dragged_card.winfo_y() + delta_y
        dragged_card.place(x=x, y=y)

def on_release(event, window, frames):
    global dragged_card
    if dragged_card:
        target_widget = window.winfo_containing(event.x_root, event.y_root)
        for col, frame in frames.items():
            if target_widget == frame or target_widget.winfo_parent() == frame:
                drop(dragged_card, frame)
                break
        else:
            drop(dragged_card, dragged_card.original_frame)  # 如果没有找到目标框架，则返回原始框架
        dragged_card = None

def drop(card_frame, target_frame):
    card_frame.place_forget()
    create_card(target_frame, card_frame.task_name, card_frame.priority, card_frame.due_date, card_frame.image_path)
    card_frame.destroy()

def create_card(frame, task_name, priority, due_date, image_path):
    try:
        card_frame = tk.Frame(frame, relief=tk.RAISED, borderwidth=1, padx=10, pady=10)
        card_frame.pack(fill=tk.X, pady=5)

        task_label = tk.Label(card_frame, text=f"Task: {task_name}", anchor='w')
        task_label.pack(fill=tk.X)
        priority_label = tk.Label(card_frame, text=f"Priority: {priority}", anchor='w')
        priority_label.pack(fill=tk.X)
        due_date_label = tk.Label(card_frame, text=f"Due Date: {due_date}", anchor='w')
        due_date_label.pack(fill=tk.X)
        edit_button = tk.Button(card_frame, text="Edit", command=lambda: edit_task(card_frame, task_name, priority, due_date, image_path))
        edit_button.pack(anchor='s')
        delete_button = tk.Button(card_frame, text="Delete", command=lambda: delete_card(card_frame))
        delete_button.pack(anchor='s')
        created_time_label = tk.Label(card_frame, text=f"Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", anchor='w')
        created_time_label.pack(fill=tk.X)

        if image_path:
            try:
                img = Image.open(image_path)
                img = img.resize((100, 100))
                img = ImageTk.PhotoImage(img)
                image_label = tk.Label(card_frame, image=img)
                image_label.image = img
                image_label.pack()
            except IOError:
                messagebox.showerror("Error loading image", "The image file could not be opened or read.")

        # 绑定拖动相关的事件
        card_frame.bind('<Button-1>', lambda e, cf=card_frame: on_press(e, cf))
        card_frame.bind('<B1-Motion>', on_drag)
        card_frame.bind('<ButtonRelease-1>', lambda e: on_release(e, frame.master, frame))

        # 保存卡片信息
        card_frame.task_name = task_name
        card_frame.priority = priority
        card_frame.due_date = due_date
        card_frame.image_path = image_path
        card_frame.original_frame = frame  # 记录原始框架

    except Exception as e:
        messagebox.showerror("Error creating card", str(e))

def edit_task(card_frame, current_task_name, current_priority, current_due_date, current_image_path):
    try:
        edit_dialog = tk.Toplevel(card_frame.master)
        edit_dialog.title("Edit Task")
        edit_dialog.geometry("400x300")

        task_name_var = tk.StringVar(value=current_task_name)
        priority_var = tk.StringVar(value=current_priority)
        due_date_var = tk.StringVar(value=current_due_date)
        image_path_var = tk.StringVar(value=current_image_path)

        task_name_label = tk.Label(edit_dialog, text="Task Name:")
        task_name_label.pack(pady=5)
        task_name_entry = tk.Entry(edit_dialog, textvariable=task_name_var)
        task_name_entry.pack(pady=5)

        priority_label = tk.Label(edit_dialog, text="Priority:")
        priority_label.pack(pady=5)
        priority_options = ["High", "Medium", "Low"]
        priority_menu = tk.OptionMenu(edit_dialog, priority_var, *priority_options)
        priority_menu.pack(pady=5)

        due_date_label = tk.Label(edit_dialog, text="Due Date (YYYY-MM-DD):")
        due_date_label.pack(pady=5)
        due_date_entry = DateEntry(edit_dialog, textvariable=due_date_var, date_pattern='yyyy-mm-dd')
        due_date_entry.pack(pady=5)

        def select_image():
            try:
                filename = filedialog.askopenfilename(title="Select Image", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif")])
                if filename:
                    image_path_var.set(filename)
            except Exception as e:
                messagebox.showerror("Image Selection Error", str(e))

        def on_confirm():
            if not task_name_var.get() or not priority_var.get() or not due_date_var.get():
                messagebox.showerror("Input Error", "All fields are required.")
                return
            new_task_name = task_name_var.get()
            new_priority = priority_var.get()
            new_due_date = due_date_entry.get_date().strftime('%Y-%m-%d')
            new_image_path = image_path_var.get()

            for widget in card_frame.winfo_children():
                if isinstance(widget, tk.Label) and widget.cget('text').startswith("Task:"):
                    widget.config(text=f"Task: {new_task_name}")
                elif isinstance(widget, tk.Label) and widget.cget('text').startswith("Priority:"):
                    widget.config(text=f"Priority: {new_priority}")
                elif isinstance(widget, tk.Label) and widget.cget('text').startswith("Due Date:"):
                    widget.config(text=f"Due Date: {new_due_date}")
                elif isinstance(widget, tk.Label) and hasattr(widget, 'image'):
                    if new_image_path:
                        try:
                            img = Image.open(new_image_path)
                            img = img.resize((100, 100))
                            img = ImageTk.PhotoImage(img)
                            widget.config(image=img)
                            widget.image = img
                        except IOError:
                            messagebox.showerror("Error loading image", "The image file could not be opened or read.")
            edit_dialog.destroy()
            save_tasks()  # 保存任务数据到JSON文件

        confirm_button = tk.Button(edit_dialog, text="Confirm", command=on_confirm)
        confirm_button.pack(pady=10)
        select_image_button = tk.Button(edit_dialog, text="Select Image", command=select_image)
        select_image_button.pack(pady=5)

    except Exception as e:
        messagebox.showerror("Error editing task", str(e))

def delete_card(card_frame):
    card_frame.destroy()
    save_tasks()  # 保存任务数据到JSON文件

def add_task(task_name, priority, due_date, image_path, dialog, frames):
    try:
        if not task_name or not priority or not due_date:
            raise ValueError("You must enter all fields")
        datetime.strptime(due_date, '%Y-%m-%d')
        create_card(frames["To_Do"], task_name, priority, due_date, image_path)
        dialog.destroy()
        save_tasks()  # 保存任务数据到JSON文件
    except ValueError as ve:
        messagebox.showerror("Error", str(ve))
    except Exception as e:
        messagebox.showerror("Unknown error", str(e))

def create_card_dialog(frames):
    dialog = tk.Toplevel(frames["To_Do"].master)
    dialog.title("Create New Task")
    dialog.geometry("400x300")

    task_name_var = tk.StringVar()
    priority_var = tk.StringVar(value="High")
    due_date_var = tk.StringVar(value=datetime.now().strftime('%Y-%m-%d'))
    image_path_var = tk.StringVar()

    task_name_label = tk.Label(dialog, text="Task Name:")
    task_name_label.pack(pady=5)
    task_name_entry = tk.Entry(dialog, textvariable=task_name_var)
    task_name_entry.pack(pady=5)

    priority_label = tk.Label(dialog, text="Priority:")
    priority_label.pack(pady=5)
    priority_options = ["High", "Medium", "Low"]
    priority_menu = tk.OptionMenu(dialog, priority_var, *priority_options)
    priority_menu.pack(pady=5)

    due_date_label = tk.Label(dialog, text="Due Date (YYYY-MM-DD):")
    due_date_label.pack(pady=5)
    due_date_entry = DateEntry(dialog, textvariable=due_date_var, date_pattern='yyyy-mm-dd')
    due_date_entry.pack(pady=5)

    def select_image():
        try:
            filename = filedialog.askopenfilename(title="Select Image", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif")])
            if filename:
                image_path_var.set(filename)
        except Exception as e:
            messagebox.showerror("Image Selection Error", str(e))

    def on_confirm():
        if not task_name_var.get() or not priority_var.get() or not due_date_var.get():
            messagebox.showerror("Input Error", "All fields are required.")
            return
        add_task(task_name_var.get(), priority_var.get(), due_date_entry.get_date().strftime('%Y-%m-%d'), image_path_var.get(), dialog, frames)

    confirm_button = tk.Button(dialog, text="Confirm", command=on_confirm)
    confirm_button.pack(pady=10)
    select_image_button = tk.Button(dialog, text="Select Image", command=select_image)
    select_image_button.pack(pady=5)

def save_tasks():
    try:
        tasks = []
        for col in ["To_Do", "In Progress", "Done"]:
            for child in frames[col].winfo_children():
                if isinstance(child, tk.Frame):
                    task_data = {
                        'name': '',
                        'priority': '',
                        'due_date': '',
                        'image_path': '',
                    }
                    for widget in child.winfo_children():
                        if isinstance(widget, tk.Label):
                            text = widget.cget('text')
                            if text.startswith('Task:'):
                                task_data['name'] = text.split(': ')[1]
                            elif text.startswith('Priority:'):
                                task_data['priority'] = text.split(': ')[1]
                            elif text.startswith('Due Date:'):
                                task_data['due_date'] = text.split(': ')[1]
                        elif isinstance(widget, tk.PhotoImage):
                            # 假设你有一个方式获取图片路径
                            task_data['image_path'] = widget.file
                    tasks.append(task_data)
        data_manager.save_data(tasks)
    except Exception as e:
        messagebox.showerror("Error saving tasks", str(e))